package com.guxingke.typecho4j.jfinal.controller;

import com.guxingke.typecho4j.Typecho4jException;
import com.guxingke.typecho4j.widget.WidgetDispatcher;
import com.guxingke.typecho4j.widget.WidgetFactory;
import com.guxingke.typecho4j.widget.dispatcher.DefaultDispatcherWidget;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;

/**
 * typecho4j的核心处理器，所有的请求都会经由此处理器进行处理。
 * 
 * @author guxingke
 * */
public class CoreController extends Controller {

	/**
	 * 前台请求处理
	 * */
	public void index() {
		dispatcher(DefaultDispatcherWidget.class);
	}

	/**
	 * 动作action,响应之后的视图分发由具体的组件负责
	 * */
	@Before(ActionAccessIntercepter.class)
	public void action() {
		dispatcher(DefaultDispatcherWidget.class);
	}

	/**
	 * 后台请求处理
	 * */
	@Before(AuthIntercepter.class)
	public void admin() {
		dispatcher(DefaultDispatcherWidget.class);
	}

	private void dispatcher(
			Class<? extends WidgetDispatcher> dispatcherClass) {
		WidgetDispatcher dispatcher = WidgetFactory
				.dispatcher(dispatcherClass);

		try {
			dispatcher.dispatcher(this);
		} catch (Typecho4jException e) {
			if (e.getErrorCode() == 404) {
				renderError(404);
			} else if (e.getErrorCode() == 500) {
				renderError(500);
			} else if (e.getErrorCode() == 700
					|| e.getErrorCode() == 701) {
				redirect("/user?errorCode=" + e.getErrorCode());
			} else if (e.getErrorCode() == 702
					|| e.getErrorCode() == 703) {
				redirect("/admin/profile?errorCode="
						+ e.getErrorCode()
						+ "#change-password");
			}
		}
	}
}
